/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-08-27 09:10:12
 * @LastEditors: 商晓彬
 * @LastEditTime: 2021-11-17 10:50:35
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TreeNode } from 'primeng/api';
import { MessageService } from '@abp/message/message.service';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { MaterialsServiceProxy } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { TableOperationComponent } from './table-operation/table-operation.component';
import { TreeOperationComponent } from './tree-operation/tree-operation.component';
@Component({
    selector: 'app-tool-modeling',
    templateUrl: './tool-modeling.component.html',
    styleUrls: ['./tool-modeling.component.less']
})
export class ToolModelingComponent extends AppComponentBase {
    @ViewChild('TableOperationComponent') TableOperationComponent: TableOperationComponent;
    @ViewChild('TreeOperationComponent') TreeOperationComponent: TreeOperationComponent;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    files2: any;//树形结构
    selectedFiles: TreeNode;// 选择树节点数据
    ischeckTree: any;//当前点击节点
    loadingtree: boolean;
    searchItem = undefined;// 左侧查询条件
    // 右侧查询条件
    material = '';
    materialType = '';// 物料类别
    model = '';
    selectRow: any;// 选中行
    rowdata: any;// 子级传入数据
    title = '';
    display: boolean = false;
    uploadedFiles = [];
    uploadUrl: any;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _materialsServiceProxy: MaterialsServiceProxy,
        private _fileDownloadService: FileDownloadService,
    ) {
        super(injector);
    }
    ngOnInit() {
        this.getTreeInfo(false);
    }
    nodeSelect(event): void {
        // 树节点点击事件
        this.ischeckTree = event.node;
        if (this.ischeckTree.levelNum != 0 && this.ischeckTree.hasChild) {
            this.loadingtree = true;
            this._materialsServiceProxy.getTreeGrid(this.ischeckTree.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    let rowInfo = this.getTreeRecursion(this.files2, this.ischeckTree.id);
                    rowInfo.children = result;
                    this.loadingtree = false;
                });
        }
        if (this.ischeckTree.levelNum != 0) {
            //关联右侧
            this.getTableList(this.ischeckTree);
        }
    }
    getTreeInfo(content): void {
        this.loadingtree = true;
        let id = 'FA568B8C-4EB5-47B1-92B1-F5AAFF234DE4'
        this._materialsServiceProxy.getTreeGrid(id)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                // 获取新增之前的数据
                let oldNode = this.files2;
                //建立父级节点
                this.files2 = [{
                    id: 'fa568b8c-4eb5-47b1-92b1-f5aaff234de4',
                    parentCode: 'fa568b8c-4eb5-47b1-92b1-f5aaff234de4',
                    materialTypeName: '物料',
                    levelNum: 0,
                    children: result ? result : []
                }];
                if (!content) {
                    // true为继承之前展开用于新增删除 false为初始加载
                    this.expandAll();
                }
                if (content) {
                    this.exdents(oldNode);
                }
                this.ischeckTree = {};
                this.loadingtree = false;
            });
    }
    // 递归循环树级结构 获取对象 通过物料ID 递归
    getTreeRecursion(data, current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getTreeRecursion(item.children, current);
            }
        }
        return result;
    }
    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    //展开全部
    expandAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }
    // 折叠
    collapseAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, false);
        });
    }
    // 新增后继承展开
    exdents(oldNode) {
        for (let i = 0; i < this.files2.length; i++) {
            if (this.files2[i].id == oldNode[i].id) {
                this.exdentsNode(oldNode[i], this.files2[i]);
            }
        }
    }
    private exdentsNode(oldNode, newNode) {
        if (oldNode != undefined) {
            if (oldNode.id == newNode.id) {
                newNode.expanded = oldNode.expanded;
                if (newNode.children) {
                    for (let i = 0; i < newNode.children.length; i++) {
                        this.exdentsNode(oldNode.children[i], newNode.children[i]);
                    }
                }
            }
        }
    }
    //新增BOP树结构
    insertBopTree(key): void {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        if (parseInt(this.ischeckTree.nodeLevel) + 1 > 3 && key) {
            this._messageService.info('节点最多只能添加四级');
            return;
        }
        setTimeout(() => {
            // 打开弹窗
            this.TreeOperationComponent.show(key, this.ischeckTree);
        }, 10)
    }
    //删除bop节点
    deleteItem(): void {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        if (this.ischeckTree.levelNum == 0) {
            this._messageService.info('该节点不可删除');
            return;
        }
        this.message.confirm(
            '确认删除' + this.ischeckTree.materialTypeName + '吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    this._materialsServiceProxy
                        .deleteNode(this.ischeckTree.id)
                        .subscribe(() => {
                            this.getTreeInfo(true);
                            this._messageService.success('删除成功');
                        });
                }
            }
        );
    }

    reset() {
        // 重置
        this.model = '';
        this.material = '';
        this.materialType = '';
    }
    import() {
        if (this.ischeckTree == undefined) {
            this._messageService.error('请选择物料');
            return;
        }
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.error('请选择物料');
            return;
        }
        // 导入
        this.display = true;
    }
    /**
     * 下载模板
     */
    down() {
        let url = "http://localhost:4200/assets/common/excel/supp.xls";
        window.open(url);
        URL.revokeObjectURL(url);
    }
    myUploader(event) {
        let files = { data: undefined, fileName: event.files[0].name };
        files.data = event.files[0];
        this._materialsServiceProxy.getExcelToMaterialsContent(
            this.ischeckTree.id,
            files
        ).pipe(finalize(() => this.primengSonTableHelper.hideLoadingIndicator())).subscribe(result => {
            if (result.code == 0) {
                this._messageService.success("导入成功！");
                this.uploadedFiles = [];
                this.display = false;
                this.getTableList(this.ischeckTree);
            } else {
                this._messageService.error(result.message);
                this.uploadedFiles = [];
                this.display = false;
            }
        });
    }

    export() {
        if (this.selectRow == undefined) {
            this._messageService.error('请选择物料');
            return;
        }
        if (Object.keys(this.selectRow).length == 0) {
            this._messageService.error('请选择物料');
            return;
        }
        //导出
        // this._materialsServiceProxy.getMaterialsContentToExcel(
        //     this.selectRow
        // ).pipe(finalize(() => this.primengSonTableHelper.hideLoadingIndicator())).subscribe(result => {
        //     this._fileDownloadService.downloadTempFile(result);
        // });
    }
    delete(row) {
        this.message.confirm(
            '确认删除这条数据吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    this._materialsServiceProxy.deleteMaterialsContent(
                        row.id,
                    ).pipe(finalize(() => this.primengSonTableHelper.hideLoadingIndicator())).subscribe(result => {
                        this._messageService.success('删除成功！');
                        this.getTableList(this.ischeckTree);
                    });
                }
            }
        );

    }
    // 获取右侧表格数据
    getTableList(row: any, event?: LazyLoadEvent) {
        // this._materialsServiceProxy.getmaterialsContentByNode(
        //     this.material,
        //     row.id,
        //     row.id,
        //     row.materialTypeCode,
        //     this.model,
        //     this.materialType,
        //     this.primengTableHelper.getSorting(this.dataTable),
        //     this.primengTableHelper.getMaxResultCount(this.paginator, event),
        //     this.primengTableHelper.getSkipCount(this.paginator, event)
        // ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
        //     this.primengTableHelper.totalRecordsCount = result.totalCount;
        //     this.primengTableHelper.records = result.items;
        //     this.primengTableHelper.hideLoadingIndicator();
        // });
    }
    addOrUpdate(row?: any) {
        if (this.ischeckTree.levelNum == 0) {
            this._messageService.error('不可以选择该节点');
            return;
        }
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.error('请选择节点');
            return;
        }
        this.rowdata = row;
        if (row != undefined) {
            this.title = '修改物料';
        } else {
            this.title = '新增物料';
        }
        setTimeout(() => {
            this.TableOperationComponent.show();
        }, 10)


    }

}
